package com.wk.code.wkserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wk.code.wkserver.entity.SysConfig;
import com.wk.code.wkserver.exception.BizException;
import com.wk.code.wkserver.mapper.SysConfigMapper;
import com.wk.code.wkserver.request.admin.SysConfigRequest;
import com.wk.code.wkserver.response.base.PageInfo;
import com.wk.code.wkserver.service.ISysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author: wangqiang
 * @create: 2021-08-27 10:03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {
    @Override
    public void add(SysConfigRequest req) {
        SysConfig selectOne = baseMapper.selectOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getFieldKey, req.getFieldKey()));
        if (Objects.nonNull(selectOne)) {
            throw new BizException("该系统配置已添加");
        }
        SysConfig sysConfig = new SysConfig();
        BeanUtils.copyProperties(req, sysConfig);
        save(sysConfig);
    }

    @Override
    public void update(SysConfigRequest req) {
        SysConfig sysConfig = new SysConfig();
        BeanUtils.copyProperties(req, sysConfig);
        updateById(sysConfig);
    }

    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    @Override
    public SysConfig detail(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysConfig> page(SysConfigRequest req) {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(req.getDescription()), SysConfig::getDescription, req.getDescription());
        wrapper.orderByDesc(SysConfig::getCreateTime);
        IPage<SysConfig> typeIPage = baseMapper.selectPage(req.page(), wrapper);
        return PageInfo.buildPage(typeIPage);
    }

    @Override
    public SysConfig selectByFieldValue(String fieldKey) {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysConfig>().
                eq(SysConfig::getFieldKey, fieldKey).last("limit 1"));
    }
}
